<?php

namespace app\common\JWTToken;

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;

class TokenUtil
{


    public function createToken($appId = null, $code = null,$expiration)
    {
        $secret_key = 'h7cwn3&eoq(j_j4@32';

        $builder = new Builder();
        $builder->issuedBy('app_a')  // 发行者，表示应用 A
        ->expiresAt($expiration)  //过期时间
        ->withClaim($appId, $code);  // 用户标识，可以是用户名、用户 ID 等

        $signer = new Sha256();
        $key = new \Lcobucci\JWT\Signer\Key($secret_key);

        $token = $builder->getToken($signer, $key);

        return $token->toString();
    }

    public function validateToken($tokenString,$userId)
    {
        $secret_key = 'h7cwn3&eoq(j_j4@32';
        $token = (new Parser())->parse($tokenString);

        $signer = new Sha256();
        $key = new \Lcobucci\JWT\Signer\Key($secret_key);

        if ($token->verify($signer, $key) && $token->validate(new ValidationData())) {
            // Token 验证通过，可以获取用户信息
            return $userId = $token->getClaim($userId);
        } else {
            return "Invalid token";
        }
    }
}